<?php
namespace app\common\lib;
use think\Exception;

/**
 * Created by PhpStorm.
 * User: shenyb
 * Date: 2018/1/18
 * Time: 17:28
 */
class Component
{

    /**
     * Created by PhpStorm.
     * User: TianFeng
     * Date: 2017/9/27
     * Time: 10:47
     * 公共方法类
     */

    //curl http方法
   function curl($url, $data, $opt = [])
    {
        $ch = curl_init();
        $header = isset($opt['header']) ? $opt['header'] : [];
        $post = isset($opt['post']) ? $opt['post'] : 1;
        $SSL_VERIFYPEER = isset($opt['SSL_VERIFYPEER']) ? $opt['SSL_VERIFYPEER'] : 0;
        //$SSL_VERIFYHOST = isset($opt['SSL_VERIFYHOST'])?$opt['SSL_VERIFYHOST']:0;
        $timeout = 300;
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_REFERER, 0);
        curl_setopt($ch, CURLOPT_POST, $post);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $SSL_VERIFYPEER);
        if (version_compare(phpversion(), '5.4.0', '<')) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1);
        } else {
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
        }
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        $handles = curl_exec($ch);
        if (curl_errno($ch)) {
            return curl_error($ch);
        }
        curl_close($ch);
        return $handles;
    }


    //get请求
   function curlget($link)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $link);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLINFO_HEADER_OUT, TRUE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        $output = curl_exec($ch);
        $int_StatusCode = curl_getinfo($ch,CURLINFO_HTTP_CODE);
        if($int_StatusCode != 200){
            throw new \Exception('请求service产生错误');
        }
        curl_close($ch);
        return $output;
    }


//POST提交获取返回值
 function post_to_url($url, $post_data = array())
    {
        $o = "";
        foreach ($post_data as $k => $v) {
            $o .= "$k=" . urlencode($v) . "&";
        }
        $post_data = substr($o, 0, -1);

        $header[] = "Content-type:text/xml";//定义content-type为xml
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLINFO_HEADER_OUT, TRUE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $rs = curl_exec($ch);
        $int_StatusCode = curl_getinfo($ch,CURLINFO_HTTP_CODE);
        if($int_StatusCode != 200){
            throw new \Exception('请求service产生错误');
        }
        if (curl_errno($ch)) {
            print curl_error($ch);
        }
        curl_close($ch);
        return $rs;
    }

//根据身份证号判断年龄
    static function getAgeByID($id)
    {
        //过了这年的生日才算多了1周岁
        if (empty($id)) return '';
        $date = strtotime(substr($id, 6, 8));
        //获得出生年月日的时间戳
        $today = strtotime('today');
        //获得今日的时间戳
        $diff = floor(($today - $date) / 86400 / 365);
        //得到两个日期相差的大体年数
        //strtotime加上这个年数后得到那日的时间戳后与今日的时间戳相比
        $age = strtotime(substr($id, 6, 8) . ' +' . $diff . 'years') > $today ? ($diff + 1) : $diff;
        return $age;
    }

//用户ID按26取余数分散到26个文件夹保存
    function uid2files($uid)
    {
        $array = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z');
        $residue = $uid % 26;
        return $array[$residue];
    }

//Sinapay接口签名
  function create_sinapay_token()
    {
        $str = md5("CEB*%!*Hx001" . date("YmdH", time()));
        return $str;
    }

//金额转大写
   function money_to_cnstr($num)
    {
        $c1 = "零壹贰叁肆伍陆柒捌玖";
        $c2 = "分角元拾佰仟万拾佰仟亿";
        $num = round($num, 2);
        $num = $num * 100;
        if (strlen($num) > 10) {
            return "数据太长，没有这么大的钱吧，检查下";
        }
        $i = 0;
        $c = "";
        while (1) {
            if ($i == 0) {
                $n = substr($num, strlen($num) - 1, 1);
            } else {
                $n = $num % 10;
            }
            $p1 = substr($c1, 3 * $n, 3);
            $p2 = substr($c2, 3 * $i, 3);
            if ($n != '0' || ($n == '0' && ($p2 == '亿' || $p2 == '万' || $p2 == '元'))) {
                $c = $p1 . $p2 . $c;
            } else {
                $c = $p1 . $c;
            }
            $i = $i + 1;
            $num = $num / 10;
            $num = (int)$num;
            if ($num == 0) {
                break;
            }
        }
        $j = 0;
        $slen = strlen($c);
        while ($j < $slen) {
            $m = substr($c, $j, 6);
            if ($m == '零元' || $m == '零万' || $m == '零亿' || $m == '零零') {
                $left = substr($c, 0, $j);
                $right = substr($c, $j + 3);
                $c = $left . $right;
                $j = $j - 3;
                $slen = $slen - 3;
            }
            $j = $j + 3;
        }

        if (substr($c, strlen($c) - 3, 3) == '零') {
            $c = substr($c, 0, strlen($c) - 3);
        }
        if (empty($c)) {
            return "零元整";
        } else {
            return $c . "整";
        }
    }


    static function get_times($arr = array())
    {
        if (isset($arr['time']) && $arr['time'] != "") {
            $time = $arr['time'];
        } else if (isset($arr['date']) && $arr['date'] != "") {
            $time = strtotime($arr['date']);
        } else {
            $time = time();
        }
        if (isset($arr['type']) && $arr['type'] != "") {
            $type = $arr['type'];
        } else {
            $type = "month";
        }
        if (isset($arr['num']) && $arr['num'] != "") {
            $num = $arr['num'];
        } else {
            $num = 1;
        }

        $thisMonthTime = 0;

        if ($type == "month") {
            $month = date("m", $time);
            $year = date("Y", $time);
            $_get_month = strtotime("{$num}month", $time);
            $_get_month_number = ( integer )date("m", $_get_month);
            if (12 < $month + $num) {
                $lastMonth = $month + $num - 12;
                $year += 1;
            } else {
                $lastMonth = $month + $num;
            }
            if ($lastMonth != $_get_month_number) {
                $thisMonthTime = strtotime("-1 day", strtotime("{$year}-{$_get_month_number}-01"));
            }
        } else {
            $thisMonthTime = strtotime("{$num}{$type}", $time);
        }
        if (isset($arr['format']) && $arr['format'] != "") {
            return date($arr['format'], $thisMonthTime);
        }
        return $thisMonthTime;
    }

//判断文件夹是否存在 如果不存在则创建
    /**
     * @param $url  string 文件夹路由
     * @return bool
     */
     function create_dir($url)
    {
        if (empty($url)) {
            return false;
        }
        if (file_exists($url)) {
            return true;
        } else {
            if (mkdir($url, 0777, true)) {
                return true;
            } else {
                return false;
            }
        }
    }

//将文件夹生成压缩文件
    /**
     * @param $zipname  string 压缩文件的路由
     * @param $file     string   要压缩的文件夹路由
     * @param $zipFilePath
     * @return bool
     */
     function create_zip($zipname, $file, $zipFilePath)
    {
        $zip = new \ZipArchive();
        if ($zip->open($zipname, \ZipArchive::CREATE) === TRUE) {
            $this->addFileToZip($file, $zip, $zipFilePath); //调用方法，对要打包的根目录进行操作，并将ZipArchive的对象传递给方法
            $zip->close(); //关闭处理的zip文件
            return true;
        } else {
            return false;
        }
    }

// 将目录下所有的文件进行压缩
     function addFileToZip($path, \ZipArchive $zip, $zipFilePath)
    {
        $handler = opendir($path); //打开当前文件夹由$path指定。
        while (($filename = readdir($handler)) !== false) {
            if ($filename != "." && $filename != "..") {//文件夹文件名字为'.'和‘..’，不要对他们进行操作
                if (is_dir($path . "/" . $filename)) {// 如果读取的某个对象是文件夹，则递归
                    $this->addFileToZip($path . "/" . $filename, $zip, $zipFilePath);
                } else { //将文件加入zip对象
                    $zip->addFile($path . "/" . $filename, $zipFilePath . $filename);
                }
            }
        }
        @closedir($path);
    }
}